﻿using System;
using System.Threading;

namespace MyDemo.Threads
{
    /// <summary>
    /// 测试一般静态字段与有ThreadStatic 标记的静态字段在
    /// 多线程执行中的区别
    /// </summary>
    public class ThreadStaticDemo
    {
        public static void Run()
        {
            MyStaticFiledClass myStaticTest = new MyStaticFiledClass();
            //
            ThreadStart ts1 = new ThreadStart(myStaticTest.AddXY);
            Thread t1 = new Thread(ts1);
            Thread t2 = new Thread(ts1);
            //
            t1.Start();
            t2.Start();
        }
    }

    internal class MyStaticFiledClass
    {
        /// <summary>
        /// 一般静态变量
        /// </summary>
        private static int X = 0;

        /// <summary>
        /// 有ThreadStatic标记的静态变量
        /// </summary>
        [ThreadStatic]
        private static int threadStaticX = 0;

        /// <summary>
        /// 分别对x,y 自增
        /// </summary>
        public void AddXY()
        {
            for (int i = 0; i < 10; i++)
            {
                X++;
                threadStaticX++;
                string info = string.Format("threadID:{0} x={1}; threadStaticX={2}",
                    Thread.CurrentThread.ManagedThreadId, X, threadStaticX);
                Console.WriteLine(info);
                Thread.Sleep(500);
            }
        }
    }
}